import pymysql


class DbUtil:

    con = None
    @classmethod
    def __connect_db(cls):

        cls.con = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
                              database="ihrm", charset="utf8")
        return cls.con
    @classmethod
    def __close_db(cls):
        cls.con.close()

    @classmethod#查询
    def query_db(cls,sql):
        cursor=None
        result=None
        try:
            # 1.创建连接
            cls.con=cls.__connect_db()
        # 2.获取游标
            cursor=cls.con.cursor()
        # 3.执行mql,获取结果集，需要返回结果
            cursor.execute(sql)
            result=cursor.fetchone()
        except Exception as err:
            print("读取数据库报错",err)
        finally:
        # 4.关闭游标
            cursor.close()
        # 5.关闭连接
            cls.__close_db()
            return result

    @classmethod
    def uid_db(cls,sql):
        cursor=None
        try:
        # 1.创建连接
            cls.con=cls.__connect_db()
        # 2.获取游标
            cursor=cls.con.cursor()
        # 3.执行mql,获取结果集，需要返回结果
            cursor.execute(sql)
            print("影响数据行数",cls.con.affected_rows())

            cls.con.commit()
        except Exception as err:
            print('增改删数据报错',err)
            cls.con.rollback()
        finally:
        # 4.关闭游标
            cursor.close()
        # 5.关闭连接
            cls.__close_db()



if __name__ == '__main__':

     sql="select * from t_book"
     print(DbUtil.query_db(sql))
     update_aql="delete from t_book where id =78"
     DbUtil.uid_db(update_aql)



